$(document).ready(function() {
    if (typeof window.console != 'object'){
        window.console = {
            log: function(){}
        };
    }
    
    var title = document.title,
	channel = nodeChat.connect("/chat"),
	message;
// TODO: handle connectionerror
	log = $("#chat-log");
	message = $("#message");
	
	// Add a button that can be easily styled
	/*$("<a></a>", {
		id: "submit",
		text: "Send",
		href: "#",
		click: function(event) {
			event.preventDefault();
			$(this).closest("form").submit();
		}
	})
	.appendTo("#footer");*/
	$("#submit").text('Send').click(function(event) {
            event.preventDefault();
            $("#chat-form").submit();
		});
	$("#myId").text('SetName').click(function(event) {
            var len = function(b) {
                if (typeof b == "undefined") {
                    return 0
                }
                var a = b.match(/[^\x00-\x80]/g);
                return (b.length + (!a ? 0 : a.length))
            };
            var n = prompt('Nick,Length <= 15 bytes','');
            if (n && len(n) <= 15){
                //console.log(channel);
                channel.setNick(n, {
                    success: function(data) {
                        $("#myId").text('Nick:' + n);
                    },
                    error: function(e) {
                        //console.log(e);
                    }
                });
            }
		});
    $('#fullWindow').attr('href',location.href).attr('target','_blank');
    // new message posted to channel
    // - add to the chat log
    $(channel).bind("msg", function(event, message) {
        //console.log('message listener');
        try{
            var time = formatTime(message.timestamp),
                row = $("<div></div>")
                    .addClass("chat-msg");
            $("<span></span>")
                .addClass("chat-time")
                .text(time)
                .appendTo(row);
            $("<span></span>")
                .addClass("chat-nick")
                .text(decodeURIComponent(message.nick))
                .appendTo(row);
            $("<span></span>")
                .addClass("chat-text")
                .text(decodeURIComponent(message.text))
                .appendTo(row);
            row.prependTo(log);
            while($('.chat-msg:last').position() && $('.chat-msg:last').position().top > $('#chat-log').height()) {
                $('.chat-msg:last').remove();
            }
        }catch(e){
            
        }
    })
    .bind("sysMsg", function(event, message) {
        //console.log('message listener');
        try{
            var time = formatTime(message.timestamp),
                row = $("<div></div>")
                    .addClass("chat-msg").addClass('chat-sysMsg');
            $("<span></span>")
                .addClass("chat-time")
                .text(time)
                .appendTo(row);
            $("<span></span>")
                .addClass("chat-nick")
                .text(decodeURIComponent(message.nick))
                .appendTo(row);
            $("<span></span>")
                .addClass("chat-text")
                .html(decodeURIComponent(message.text))
                .appendTo(row);
            row.prependTo(log);
            while($('.chat-msg:last').position() && $('.chat-msg:last').position().top > $('#chat-log').height()) {
                $('.chat-msg:last').remove();
            }
        }catch(e){
            
        }
    })
    .bind('connectionerror', function(){
        var row = $("<div></div>")
            .addClass("chat-msg");
        $("<a></a>")
            .attr('href','javascript:void(0);')
            .click(function(){location.reload();})
            .addClass("chat-error")
            .text('Connection error ,please reload .')
            .appendTo(row);
        row.prependTo(log);
    });
    
	$("#chat-form").submit(function() {
		channel.send(message.val().slice(0,50),{
            success: function(data) {
                //console.log('send success');
                if (data.errorCode){
                    var row = $("<div></div>")
                        .addClass("chat-msg");
                    $("<span></span>")
                        .addClass("chat-error")
                        .text(data.errorCode + ':' + data.error)
                        .appendTo(row);
                    row.prependTo(log);
                }
            },
            error: function(e) {
                //console.log('error',e);
            }
        });
		message.val("").focus();
		
		return false;
	});
    
    // notify the chat server that we're leaving if we close the window
    $(window).unload(function() {
        channel.part();
    });
    
   var fuckie = function(){
        $('#footer').css('top',$(window).height);
   };
   
   if ($.browser.msie&&($.browser.version == "6.0")&&!$.support.style){
       $('#footer').css('position','absolute').css('width','100%');
       fuckie();
       $(window).resize(function(){
        fuckie();
       });
   }
    function formatTime(timestamp) {
        var date = new Date(timestamp),
            hours = date.getHours(),
            minutes = date.getMinutes(),
            ampm = "AM";
        if (hours > 12) {
            hours -= 12;
            ampm = "PM";
        }
        if (minutes < 10) {
            minutes = "0" + minutes;
        }
        return hours + ":" + minutes + " " + ampm;
    }
    setTimeout(function(){
        channel.join('acmer', {
            success: function(data) {
                message.removeAttr('disabled').val('');
                message.focus();
                $("#myId").text('Nick:' + data.nick);
            },
            error: function(e) {
            }
       });
    }, 500 + Math.floor(Math.random() * 1500));
});
